/*
 *  group.c
 *
 *  Group Operations
 *
 *  Copyright (C) 2008  Huang Guan
 *
 *  2008-7-12 Created.
 *
 *  Description: This file mainly includes the functions about 
 *
 */

#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include "qqclient.hpp"

#include "debug.hpp"
#include "protocol.hpp"
#include "group.hpp"

namespace {
	struct searcher:public std::binary_function<qqgroup*,uint,bool>{
	bool operator() (const qqgroup *p,  uint v) const{
		return p->number ==v ;
	}
};
}


qqgroup* group_get( qqclient* qq, uint number, int create )
{
	if( !number )
		return NULL;
	qqgroup* g=NULL;
	qq->group_list_lock.lock();
	qqclient::group_list_type::iterator i=std::find_if(qq->group_list.begin(),qq->group_list.end(),std::bind2nd(searcher(),number));
	if(i!=qq->group_list.end()) g=*i;

	//if not found, g must be NULL
	if( !g && create ){
		g=new qqgroup();
		g->number = number;
		g->name=QString::number(number);
		qq->group_list.push_back(g);
	}
	qq->group_list_lock.unlock();
	return g;
}

void group_remove( qqclient* qq, uint number )
{
	qq->group_list_lock.lock();	
	qqclient::group_list_type::iterator i=std::find_if(qq->group_list.begin(),qq->group_list.end(),std::bind2nd(searcher(),number));
	if(i!=qq->group_list.end()) {
		qq->group_list.erase(i);
	}
	qq->group_list_lock.unlock();	
}

void group_update_list( qqclient* qq )
{
//	prot_group_download_list( qq, 0 );  不知道这个09还能不能用。
	prot_group_download_labels( qq, 0 );
}

void group_update_info( qqclient* qq, qqgroup* g )
{
}


void group_put_event( qqclient* qq )
{
	size_t tempSize=KB(1);
	char *temp=new char[tempSize];

	qqgroup* g;

	if( !temp ) return;
	strncpy( temp, "grouplist^$",tempSize-1 );
	QMutexLocker ql(&qq->group_list_lock);
	for(qqclient::group_list_type::iterator i=qq->group_list.begin();
		i!=qq->group_list.end();++i){
		g = *i;
		QByteArray ba=g->name.toUtf8();
		qsnprintf( temp,tempSize-1, "%s%u\t%s^@", temp, g->number, ba.data());
	}	
	qqclient_put_event( qq, temp );
	delete[] temp ;
}
